
package com.sausageking.auth;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.NotFoundException;
import com.sausageking.server.dao.GenericDao;
import com.sausageking.shared.Consumer;
import com.sausageking.shared.LoginToken;

public class LoginTokenDao {

  /**
   * Create a new login token for this user.
   */
  public Key<LoginToken> setupNewLoginToken(Consumer consumer) {
    GenericDao<LoginToken> dao = new GenericDao<LoginToken>(LoginToken.class);
    LoginToken loginToken = new LoginToken();
    loginToken.setOwner(consumer);
    return dao.put(loginToken);
  }

  /**
   * If the {@code tokenId} is valid, consider this user is logged in. return
   * the associated user. Otherwise, return {@code null}.
   */
  public Consumer loginWithToken(String tokenId) {
    GenericDao<LoginToken> dao = new GenericDao<LoginToken>(LoginToken.class);
    LoginToken loginToken;
    try {
      loginToken = dao.get(tokenId);
      GenericDao<Consumer> consumerDao = new GenericDao<Consumer>(
          Consumer.class);
      return consumerDao.get(loginToken.getOwner());
    } catch (NotFoundException e) {
      return null;
    }
  }
}